<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\AuthController;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Token;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Validator;

class AdminController extends Controller
{
    public function getAdmin(Admin $admin){
        $result = $admin->get(['username' , 'last_login_timestamp' , 'created_at'])->toArray();
        return view('admin' , ['data' => $result]);
    }

    public function adminView(){
        return view('login');
    }

    public function adminSignIn(Request $request, AuthController $authController){
        $only = $request->only(['username' , 'password']);

        $validator = Validator::make($only , [
            'username' => 'required|min:4|max:60',
            'password' => 'required|min:8|max:60'
        ] , []);

        if ($validator->fails()){
            return redirect('Module_C/admin')->with('error' , $validator->errors()->messages());
        }

        $only['password'] = $authController->setPwd($only['password']);

        $admin = Admin::where($only);

        if ($admin->first() == null){
            return redirect('Module_C/admin')->with('error' , ['username&password' => ['Account or password error']]);
        }

        $admin->update(['last_login_timestamp' => time()]);

        $token = $authController->setToken($admin->first()->id , 1);
        Cookie::queue('token' , $token , '1440');
        return redirect('Module_C/adminList');
    }

    public function adminSignUp(){
        Token::where('token' , Cookie::get('token'))->delete();

        return redirect('Module_C/admin')->withCookie(Cookie::forget('token'));
    }
}
